package com.bw.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.common.base.BaseFragment
import com.bw.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * MVI模式下的BaseFragment(意图和状态)
 */
abstract class BaseMviFragment<T:ViewDataBinding>:BaseFragment<T>() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        var rootView=super.onCreateView(inflater, container, savedInstanceState)
        initData()
        updateUi()
        EventBus.getDefault().register(this)
        return rootView
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event: CustomEvent){
        if(event!=null&& event.terget==this::class.java.simpleName){
            handEvent(event)
        }
    }

    open fun handEvent(event: CustomEvent){

    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()

    }

    private fun updateUi(){
        //启动协程更新ui
        lifecycleScope.launch {
            //当页面能看见的时候，渲染发生的时候，但是还没有获取焦点(在之前没必要)
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }


    open suspend fun collectUiState(){

    }

    private fun initData(){
        //启动协程给viewmodel发送意图intent
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    open suspend fun sendViewIntent(){

    }

}